<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  reqUserList,
  reqAddOrUpdateUser,
  reqUserRoles,
  reqAssignRole,
  reqRemoveUser,
  reqRemoveUsers,
} from "@/api/acl/user";
import { ElMessage } from "element-plus";
import useLayoutStore from "@/store/modules/layout";
// layoutStore
const layoutStore = useLayoutStore();
let pageNo = ref<number>(1);
let pageSize = ref<number>(3);
let total = ref<number>(0);
// 控制el-drawer组件的显示与隐藏
let drawerShow = ref<boolean>(false);
// userList
let userList = ref<any[]>([]);
// el-form组件实例对象
let formRef = ref();
// userParams
let userParams = reactive<any>({
  username: "",
  name: "",
  password: "",
});
// 控制点击分配角色按钮的drawer的显示与隐藏
let drawerShow1 = ref<boolean>(false);
// 控制 el-checkbox 全选按钮的字段
let checkAll = ref<boolean>(false);
// 控制不确定状态的字段
let isIndeterminate = ref<boolean>(true);
// 所有的角色列表(数组)
let allRolesList = ref<any[]>([]);
// 已勾选的角色列表(数组)
let checkedRolesList = ref<any[]>([]);
// 搜索的用户名
let keyword = ref<string>("");
// onMounted
onMounted(() => {
  getUserList();
});
// 要批量删除的id列表
let removeIdList = ref<number[]>([]);
// 封装出的获取用户列表的方法
const getUserList = async (pager = 1) => {
  pageNo.value = pager;
  let res: any = await reqUserList(pageNo.value, pageSize.value, keyword.value);
  if (res.code == 200) {
    total.value = res.data.total;
    userList.value = res.data.records;
  }
};
// el-pagination 触发size-change的回调
const handler = (value: number) => {
  getUserList();
};
// 点击添加(用户)按钮的回调
const addUser = () => {
  // 清空数据，防止数据回显
  Object.assign(userParams, {
    username: "",
    name: "",
    password: "",
    // 清空id
    id: null,
  });
  drawerShow.value = true;
  // 执行完 drawerShow.value = true 时，无法立即获取formRef
  nextTick(() => {
    // 清空自定义验证失败提示
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
    formRef.value.clearValidate("password");
  });
};
// 点击编辑(用户)按钮的回调
const updateUser = (row: any) => {
  drawerShow.value = true;
  Object.assign(userParams, row);
  nextTick(() => {
    // 清空自定义验证失败提示
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
  });
};
// 点击 el-drawer 的确定按钮的回调
const confirm = async () => {
  // 只有当 formRef.value.validate() 返回成功的Promise才会执行后续代码，即自定义验证通过
  await formRef.value.validate();
  let res: any = await reqAddOrUpdateUser(userParams);
  if (res.code == 200) {
    // 关闭el-drawer
    drawerShow.value = false;
    // 提示
    ElMessage({
      type: "success",
      message: userParams.id ? "修改成功" : "添加成功",
    });
    // 重新获取userList： 因为要重新刷新页面，这行代码就没有意义了
    // getUserList(userParams.id ? pageNo.value : 1);
    // 重新加载页面:为了让登录在修改后的用户可以立刻退出登录
    window.location.reload();
  } else {
    drawerShow.value = false;
    ElMessage({
      type: "error",
      message: userParams.id ? "修改失败" : "添加失败",
    });
  }
};
// 点击 el-drawer 的取消按钮的回调
const cancel = () => {
  drawerShow.value = false;
};
// 点击分配角色按钮的回调
const setRole = async (user: any) => {
  drawerShow1.value = true;
  // 准备要渲染的数据(用户姓名,用户id)
  Object.assign(userParams, user);
  // 发请求获取用户角色
  let res: any = await reqUserRoles(user.id);
  if (res.code == 200) {
    allRolesList.value = res.data.allRolesList;
    checkedRolesList.value = res.data.assignRoles;
  }
};
// 点击全选按钮的回调
const handleCheckAllChange = (val: boolean) => {
  checkedRolesList.value = val ? allRolesList.value : [];
  isIndeterminate.value = false;
};
// 点击每一个checkbox的回调
const handleCheckedCitiesChange = (val: string[]) => {
  checkAll.value = val.length == allRolesList.value.length;
  isIndeterminate.value =
    val.length < allRolesList.value.length && val.length > 0;
};
// 点击分配角色的drawer组件的确定按钮的回调
const handleConfirm = async () => {
  let params = {
    userId: userParams.id,
    roleIdList: checkedRolesList.value.map((item: any) => item.id),
  };
  let res: any = await reqAssignRole(params);
  if (res.code == 200) {
    // 关闭drawer
    drawerShow1.value = false;
    // 提示成功
    ElMessage({
      type: "success",
      message: "分配角色成功",
    });
    // 重新获取用户列表
    getUserList(pageNo.value);
  } else {
    ElMessage({
      type: "error",
      message: "分配角色失败",
    });
  }
};
// popconfirm 确定删除用户的回调
const removeUser = async (id: number) => {
  let res: any = await reqRemoveUser(id);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getUserList(userList.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage({
      type: "error",
      message: "系统数据,无法删除",
    });
  }
};
// 点击批量删除的回调
const removeUsers = async () => {
  let _removeIdList: any = removeIdList.value.map((item: any) => item.id);
  let res: any = await reqRemoveUsers(_removeIdList);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "批量删除成功",
    });
    getUserList(
      userList.value.length > removeIdList.value.length
        ? pageNo.value
        : pageNo.value - 1
    );
  } else {
    ElMessage({
      type: "error",
      message: "系统数据,无法删除",
    });
  }
};
// 当用户手动勾选数据行的 Checkbox 时触发的事件
const selectionChange = (selection: any[]) => {
  removeIdList.value = selection;
};
// 点击搜索按钮的回调
const search = () => {
  getUserList();
  keyword.value = "";
};
// 点击重置按钮的回调
const reset = () => {
  layoutStore.refresh = !layoutStore.refresh;
};
// 验证username的规则
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5 && value.trim().length <= 10) {
    callback();
  } else {
    callback(new Error("用户姓名必须在五到十位之间"));
  }
};
// 验证name的规则
const validatorname = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5 && value.trim().length <= 10) {
    callback();
  } else {
    callback(new Error("用户昵称必须在五到十位之间"));
  }
};
// 验证password的规则
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5 && value.trim().length <= 10) {
    callback();
  } else {
    callback(new Error("密码必须在五到十位之间"));
  }
};
// 表单验证的规则对象
let rules = {
  username: [{ required: true, trigger: "blur", validator: validatorUsername }],
  name: [{ required: true, trigger: "blur", validator: validatorname }],
  password: [{ required: true, trigger: "blur", validator: validatorPassword }],
};
</script>

<template>
  <div>
    <el-card>
      <el-form inline class="form">
        <el-form-item label="用户名">
          <el-input v-model="keyword" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            :disabled="keyword ? false : true"
            >搜索</el-button
          >
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addUser" v-have="`btn.User.add`"
        >添加</el-button
      >
      <el-button
        type="danger"
        @click="removeUsers"
        :disabled="removeIdList.length == 0 ? true : false"
        v-have="`btn.User.remove`"
        >批量删除</el-button
      >
      <el-table border :data="userList" @selection-change="selectionChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          label="#"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="id" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名字"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center" width="250px">
          <template v-slot="{ row, $index }">
            <el-button type="primary" icon="User" @click="setRole(row)"
              >分配角色</el-button
            >
            <el-button
              type="info"
              icon="Edit"
              @click="updateUser(row)"
              v-have="`btn.User.update`"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定要删除${row.username}吗?`"
              width="250px"
              icon="Delete"
              @confirm="removeUser(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  icon="Delete"
                  v-have="`btn.User.remove`"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7]"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        background
        style="margin: 10px 0"
        @current-change="getUserList"
        @size-change="handler"
      >
      </el-pagination>
    </el-card>
    <el-drawer v-model="drawerShow">
      <template #header>
        <h4>{{ userParams.id ? "修改用户" : "添加用户" }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户姓名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="confirm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawerShow1">
      <template #header>
        <h4>分配角色用户</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input v-model="userParams.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <div>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <el-checkbox-group
                v-model="checkedRolesList"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="item in allRolesList"
                  :key="item.id"
                  :label="item"
                  >{{ item.roleName }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="drawerShow1 = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.form {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
